package me.tuyou.es.java.client;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Objects;

@Component
public class EsClient {

    @Value("${elasticsearch.rest.hosts}")
    private String hosts;
//    @Value("${elasticsearch.rest.username}")
//    private String username;
//    @Value("${elasticsearch.rest.password}")
//    private String password;

//    @ConditionalOnMissingBean(RestHighLevelClient.class)
    @Bean
    public RestHighLevelClient initClient() {
        HttpHost[] httpHosts = Arrays.stream(hosts.split(",")).map(host -> {
            String[] hostParts = hosts.split(":");
            String hostName = hostParts[0];
            int port = Integer.parseInt(hostParts[1]);
            return new HttpHost(hostName, port, HttpHost.DEFAULT_SCHEME_NAME);
        }).filter(Objects::nonNull).toArray(HttpHost[]::new);

        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }

//    @ConditionalOnProperty("elasticsearch.rest.password")
//    @Bean
//    public RestHighLevelClient initClient2() {
//        HttpHost[] httpHosts = Arrays.stream(hosts.split(",")).map(host -> {
//            String[] hostParts = hosts.split(":");
//            String hostName = hostParts[0];
//            int port = Integer.parseInt(hostParts[1]);
//            return new HttpHost(hostName, port, HttpHost.DEFAULT_SCHEME_NAME);
//        }).filter(Objects::nonNull).toArray(HttpHost[]::new);
//
//        return new RestHighLevelClient(RestClient.builder(httpHosts));
//    }
}
